/**
 * 门店和房间API客户端
 * 
 * 用途：负责获取门店列表和房间列表的HTTP请求
 * 方法：使用OkHttp库进行网络请求，Gson进行JSON反序列化
 * 原理：通过GET请求获取门店和房间数据，支持分页和筛选
 */
package com.example.brain_wave.bluetooth.api

import com.example.brain_wave.bluetooth.model.StoreResponse
import com.example.brain_wave.bluetooth.model.RoomResponse
import com.example.brain_wave.bluetooth.model.Store
import com.example.brain_wave.bluetooth.model.Room
import com.google.gson.Gson
import kotlinx.coroutines.*
import okhttp3.*
import java.io.IOException
import com.example.brain_wave.config.AppConfig
import android.content.Context

class StoreRoomApiClient(private val context: Context) {
    
    private val appConfig = AppConfig.getInstance(context)
    
    private val client = OkHttpClient.Builder()
        .connectTimeout(appConfig.connectTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .writeTimeout(appConfig.writeTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .readTimeout(appConfig.readTimeout.toLong(), java.util.concurrent.TimeUnit.SECONDS)
        .build()
    
    private val gson = Gson()
    
    // API配置
    private var baseUrl: String = ""
    private val storeEndpoint = "/admin/store/apiStores"
    private val roomEndpoint = "/admin/room/apiRooms"
    
    // 固定请求头
    private val token = "jsw2hSS8ypfheSX5"
    private val server = "1"
    
    // 回调函数
    private var onStoreListReceived: ((List<Store>) -> Unit)? = null
    private var onRoomListReceived: ((List<Room>) -> Unit)? = null
    private var onError: ((String) -> Unit)? = null
    
    /**
     * 设置API基础URL
     */
    fun setBaseUrl(url: String) {
        baseUrl = url.trimEnd('/')
    }
    
    /**
     * 设置门店列表接收回调
     */
    fun setOnStoreListReceived(callback: (List<Store>) -> Unit) {
        onStoreListReceived = callback
    }
    
    /**
     * 设置房间列表接收回调
     */
    fun setOnRoomListReceived(callback: (List<Room>) -> Unit) {
        onRoomListReceived = callback
    }
    
    /**
     * 设置错误回调
     */
    fun setOnError(callback: (String) -> Unit) {
        onError = callback
    }
    
    /**
     * 获取门店列表
     */
    fun getStoreList(limit: Int = 100, page: Int = 1) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val url = "$baseUrl$storeEndpoint?limit=$limit&page=$page"
                val request = Request.Builder()
                    .url(url)
                    .get()
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("token", token)
                    .addHeader("server", server)
                    .build()
                
                client.newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        CoroutineScope(Dispatchers.Main).launch {
                            onError?.invoke("获取门店列表失败: ${e.message}")
                        }
                    }
                    
                    override fun onResponse(call: Call, response: Response) {
                        try {
                            println("API响应状态: ${response.code} ${response.message}")
                            println("API响应头: ${response.headers}")
                            
                            if (response.isSuccessful) {
                                val responseBody = response.body
                                println("响应体对象: $responseBody")
                                
                                if (responseBody != null) {
                                    val bodyString = responseBody.string()
                                    println("API响应内容: $bodyString")
                                    
                                    if (!bodyString.isNullOrEmpty()) {
                                        try {
                                            val storeResponse = gson.fromJson(bodyString, StoreResponse::class.java)
                                            println("解析后的响应: code=${storeResponse.code}, msg=${storeResponse.msg}")
                                            
                                            CoroutineScope(Dispatchers.Main).launch {
                                                if (storeResponse.code == 1) {
                                                    println("门店数据: ${storeResponse.data.list}")
                                                    onStoreListReceived?.invoke(storeResponse.data.list)
                                                } else {
                                                    onError?.invoke("获取门店列表失败: ${storeResponse.msg}")
                                                }
                                            }
                                        } catch (e: Exception) {
                                            println("JSON解析异常: ${e.message}")
                                            CoroutineScope(Dispatchers.Main).launch {
                                                onError?.invoke("解析门店数据失败: ${e.message}")
                                            }
                                        }
                                    } else {
                                        CoroutineScope(Dispatchers.Main).launch {
                                            onError?.invoke("响应内容为空")
                                        }
                                    }
                                } else {
                                    CoroutineScope(Dispatchers.Main).launch {
                                        onError?.invoke("响应体为null")
                                    }
                                }
                            } else {
                                CoroutineScope(Dispatchers.Main).launch {
                                    onError?.invoke("服务器错误: ${response.code} ${response.message}")
                                }
                            }
                        } catch (e: Exception) {
                            println("处理响应异常: ${e.message}")
                            e.printStackTrace()
                            CoroutineScope(Dispatchers.Main).launch {
                                onError?.invoke("处理响应失败: ${e.message}")
                            }
                        }
                    }
                })
                
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    onError?.invoke("请求门店列表失败: ${e.message}")
                }
            }
        }
    }
    
    /**
     * 获取指定门店的房间列表
     */
    fun getRoomList(storeId: Int, limit: Int = 5, page: Int = 1) {
        val url = "$baseUrl$roomEndpoint?limit=$limit&page=$page&store_id=$storeId"
        val request = Request.Builder()
            .url(url)
            .get()
            .addHeader("token", token)
            .addHeader("server", server)
            .build()
        
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                CoroutineScope(Dispatchers.Main).launch {
                    onError?.invoke("获取房间列表失败: ${e.message}")
                }
            }
            
            override fun onResponse(call: Call, response: Response) {
                try {
                    response.use { resp ->
                        if (resp.isSuccessful) {
                            val responseBody = resp.body?.string() ?: ""
                            println("房间API响应: $responseBody")
                            
                            if (responseBody.isNotEmpty()) {
                                try {
                                    val roomResponse = gson.fromJson(responseBody, RoomResponse::class.java)
                                    CoroutineScope(Dispatchers.Main).launch {
                                        if (roomResponse.code == 1) {
                                            onRoomListReceived?.invoke(roomResponse.data.list)
                                        } else {
                                            onError?.invoke("获取房间列表失败: ${roomResponse.msg}")
                                        }
                                    }
                                } catch (e: Exception) {
                                    CoroutineScope(Dispatchers.Main).launch {
                                        onError?.invoke("解析房间数据失败: ${e.message}")
                                    }
                                }
                            } else {
                                CoroutineScope(Dispatchers.Main).launch {
                                    onError?.invoke("服务器返回空响应")
                                }
                            }
                        } else {
                            CoroutineScope(Dispatchers.Main).launch {
                                onError?.invoke("服务器错误: ${resp.code} ${resp.message}")
                            }
                        }
                    }
                } catch (e: Exception) {
                    CoroutineScope(Dispatchers.Main).launch {
                        onError?.invoke("处理响应失败: ${e.message}")
                    }
                }
            }
        })
    }
    
    /**
     * 同步获取门店列表（用于测试）
     */
    suspend fun getStoreListSync(limit: Int = 100, page: Int = 1): Result<List<Store>> = withContext(Dispatchers.IO) {
        try {
            val url = "$baseUrl$storeEndpoint?limit=$limit&page=$page"
            val request = Request.Builder()
                .url(url)
                .get()
                .addHeader("token", token)
                .addHeader("server", server)
                .build()
            
            val response = client.newCall(request).execute()
            
            if (response.isSuccessful) {
                val responseBody = response.body?.string() ?: ""
                val storeResponse = gson.fromJson(responseBody, StoreResponse::class.java)
                if (storeResponse.code == 1) {
                    Result.success(storeResponse.data.list)
                } else {
                    Result.failure(Exception("获取门店列表失败: ${storeResponse.msg}"))
                }
            } else {
                Result.failure(Exception("服务器错误: ${response.code} ${response.message}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 同步获取房间列表（用于测试）
     */
    suspend fun getRoomListSync(storeId: Int, limit: Int = 5, page: Int = 1): Result<List<Room>> = withContext(Dispatchers.IO) {
        try {
            val url = "$baseUrl$roomEndpoint?limit=$limit&page=$page&store_id=$storeId"
            val request = Request.Builder()
                .url(url)
                .get()
                .addHeader("token", token)
                .addHeader("server", server)
                .build()
            
            val response = client.newCall(request).execute()
            
            if (response.isSuccessful) {
                val responseBody = response.body?.string() ?: ""
                val roomResponse = gson.fromJson(responseBody, RoomResponse::class.java)
                if (roomResponse.code == 1) {
                    Result.success(roomResponse.data.list)
                } else {
                    Result.failure(Exception("获取房间列表失败: ${roomResponse.msg}"))
                }
            } else {
                Result.failure(Exception("服务器错误: ${response.code} ${response.message}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}